import java.util.HashMap;
import java.util.Map;

/**
 * 1797. 设计一个验证系统
 * https://leetcode-cn.com/problems/design-authentication-manager/
 */
public class Solutions_1797 {
    public static void main(String[] args) {
        AuthenticationManager obj = new AuthenticationManager(5);
        obj.renew("aaa", 1);
        obj.generate("aaa", 2);
        int res1 = obj.countUnexpiredTokens(6);  // output: 1
        System.out.println(res1);
        obj.generate("bbb", 7);
        obj.renew("aaa", 8);
        obj.renew("bbb", 10);
        int res2 = obj.countUnexpiredTokens(15);  // output: 0
        System.out.println(res2);
    }
}

class AuthenticationManager {
    // 键：token，值：过期时间
    private Map<String, Integer> map = null;
    private int timeToLive;

    public AuthenticationManager(int timeToLive) {
        map = new HashMap<>();
        this.timeToLive = timeToLive;
    }

    public void generate(String tokenId, int currentTime) {
        map.put(tokenId, currentTime + timeToLive);
    }

    public void renew(String tokenId, int currentTime) {
        if (map.containsKey(tokenId)) {
            // 未过期时，renew 操作
            if (map.get(tokenId) > currentTime) {
                map.put(tokenId, currentTime + timeToLive);
            }
        }
    }

    public int countUnexpiredTokens(int currentTime) {
        int res = 0;
        for (Integer value : map.values()) {
            // 未过期时，统计
            if (value > currentTime) {
                res ++;
            }
        }
        return res;
    }
}
